package com.nl.idempotent;

import com.nl.idempotent.annotation.IdemCheck;
import com.nl.idempotent.dao.IdempotentDao;
import com.google.gson.Gson;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.nl.model.exception.BizProcessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 锁拦截器.
 *
 * @author breggor
 */
@Slf4j
@Aspect
public class IdempotentAspect {

    private static final Gson GSON = new Gson();

    private static final ExpressionParser EXP_PARSER = new SpelExpressionParser();

    private static final ParameterNameDiscoverer NAME_DISCOVERER = new DefaultParameterNameDiscoverer();

    @Autowired
    private IdempotentDao idempotentDao;


    /**
     * 环绕通知.
     *
     * @param joinPoint 切面方法
     * @param idemCheck 注解
     * @return 方法返回
     * @throws Exception 处理异常
     */
    @Around(value = "@annotation(idemCheck)")
    public Object handle(final ProceedingJoinPoint joinPoint, final IdemCheck idemCheck) throws Exception {
        Assert.hasText(idemCheck.module(), "幂等模块名是必需的");
        Assert.notEmpty(idemCheck.keys(), "缺少幂等的业务key");

        if (log.isDebugEnabled()) {
            log.debug("[幂等] - 拦截进入处理");
        }

        String bizId = buildBizId(joinPoint, idemCheck);
        log.debug("[幂等] - 参数: module={}, bizId={}", idemCheck.module(), bizId);

        //检查处理结果
        if (idemCheck.test()) {
            //已处理
            if (idempotentDao.isProcessed(bizId)) {
                if (Void.class == idemCheck.resultType()) {
                    return null;
                } else {
                    String bizRes = idempotentDao.load(bizId);
                    if (!StringUtils.isEmpty(bizRes)) {
                        return parseObject(idemCheck.resultType(), bizRes);
                    }
                }
            }
        }

        Object result = null;
        try {
            //1、记录业务数据
            boolean ok = idempotentDao.begin(bizId, idemCheck.module());
            if (ok) {
                result = joinPoint.proceed();
                //2、记录业务返回值：目前json序列化
                if (Void.class != idemCheck.resultType()) {
                    idempotentDao.end(bizId, GSON.toJson(result));
                }
            }
        } catch (DuplicateKeyException ex) {
            //3、业务操作已处理过，直接去业务数据，多线程同时处理，没有处理完需要等待获取业务数据
            result = queryResult(idemCheck, bizId);
        } catch (Throwable e) {
            log.error("[幂等] - module={}, bizId={}, 业务处理异常", idemCheck.module(), bizId, e);
            if (e instanceof BizProcessException) {
                throw (BizProcessException) e;
            }
            throw new BizProcessException("业务异常", e);
        }

        return result;
    }

    /**
     * 查询已处理的结果.
     *
     * @param idemCheck idemCheck
     * @param bizId     bizId
     * @return 业务结果
     */
    private Object queryResult(final IdemCheck idemCheck, final String bizId) {
        if (Void.class != idemCheck.resultType()) {
            String result;
            do {
                result = idempotentDao.load(bizId);
            } while (StringUtils.isEmpty(result));

            return parseObject(idemCheck.resultType(), result);
        }

        return null;
    }

    /**
     * 对象json解析.
     *
     * @param type   对象类型
     * @param result 被解析内容
     * @return
     */
    private Object parseObject(final Class type, final String result) {
        try {
            return GSON.fromJson(result, type);
        } catch (Exception e) {
            log.error(String.format("[幂等] - idempotent result: %s cannot be resolved by %s", result, type));
        }
        return null;
    }

    /**
     * 异常处理.
     *
     * @param joinPoint 切面方法
     * @param idemCheck 幂等性注解
     * @param ex        异常处理
     * @throws Throwable 异常
     */
    @AfterThrowing(value = "@annotation(idemCheck)", throwing = "ex")
    public void afterThrowing(final JoinPoint joinPoint, final IdemCheck idemCheck, final Throwable ex) {
        log.error("[幂等] - 拦截内部异常", ex);
    }

    /**
     * 正常返回处理.
     *
     * @param joinPoint 切面方法
     * @param idemCheck 幂等性注解
     * @param result    正常返回值
     */
    @AfterReturning(value = "@annotation(idemCheck)", returning = "result")
    public void afterReturning(final JoinPoint joinPoint, final IdemCheck idemCheck, final Object result) {
        log.debug("[幂等] - 实际返回值：{}", result);
    }

    /**
     * 构建业务id.
     *
     * @param joinPoint 切面方法
     * @param idemCheck 幂等性注解
     * @return 业务id
     */
    private String buildBizId(final ProceedingJoinPoint joinPoint, final IdemCheck idemCheck) {
        List<String> keyList = getSpelKey(idemCheck.keys(), getMethod(joinPoint), joinPoint.getArgs());
        return StringUtils.collectionToDelimitedString(keyList, "-");
    }

    /**
     * 获取切面方法对象.
     *
     * @param joinPoint 切面方法
     * @return 切面方法对象.
     */
    private Method getMethod(final JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method.getDeclaringClass().isInterface()) {
            try {
                method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return method;
    }

    /**
     * 切面方法生成key列表.
     *
     * @param defKeys    默认key组
     * @param method     切面方法
     * @param paraValues 切面方法参数值
     * @return 生成key列表
     */
    private List<String> getSpelKey(final String[] defKeys, final Method method, final Object[] paraValues) {
        List<String> keyList = new ArrayList<>();
        EvaluationContext eva;
        Object value;
        for (String key : defKeys) {
            if (!StringUtils.isEmpty(key)) {
                eva = new MethodBasedEvaluationContext(null, method, paraValues, NAME_DISCOVERER);
                value = EXP_PARSER.parseExpression(key).getValue(eva);
                if (Objects.isNull(value)) {
                    Assert.notNull(value, String.format("幂等业务Id=%s, 值不能为null", key));
                }
                keyList.add(value.toString());
            }
        }
        return keyList;
    }
}
